package cn.wzw.test;

import cn.springboot.erp.utils.JWTUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@SpringBootTest
public class Application {

    @Resource
    private JWTUtil jwtUtil;
    @Test
    public void testMethod01(){
        // 1、设置头部
        HashMap<String, Object> header = new HashMap<>();
        header.put("alg","HS256");
        header.put("type","JWT");

        // 2、设置载荷
        HashMap<String, Object> payload = new HashMap<>();
        payload.put("name","tom");
        payload.put("age",23);

        // 3、设置生命周期
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_MONTH,7);

        // 4、设置密钥
        String secret = "java2323";

        // 5、创建token
        String token = JWT.create()
                .withHeader(header)
                .withClaim("user", payload)
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(secret));
        System.out.println("token = " + token);
    }

    @Test
    public void JWTTest(){
        /*
            Header 头部
            Payload 载荷
            Signature 签名
         */

        // 使用jwe创建token 过程
        // 1、创建Header头部
        HashMap<String,Object> header = new HashMap<>();
        header.put("alg","HS256");
        header.put("type","JWT");

        // 2、创建Payload载荷 存储用户信息
        HashMap<String,Object> payload = new HashMap<>();
        payload.put("username","小海");
        payload.put("uuid","123456");

        // 3、设置token的生命周期
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE,30);

        // 4、设置token的密钥
        String secret = "java2323";

        // 5、创建token
        String token = JWT.create()
                .withHeader(header)
                .withClaim("user", payload)
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(secret));

        System.out.println("token = " + token);
        /*
            eyJ0eXAiOiJKV1QiLCJ0eXBlIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.
            eyJleHAiOjE3MTI3NDExMzEsInVzZXIiOnsidWlkIjoiMTIzNDU2IiwidXNlcm5hbWUiOiLlsI_mtbcifX0.
            M6L1JwbJ0Ot079nDaTVPiOiLdb_AmWMDO8vgZpIrqKE
         */

        // 获取token中的用户信息
        Map<String, Object> user = JWT.decode(token).getClaim("user").asMap();
        String username = (String) user.get("username");
        String uuid = (String) user.get("uuid");
        System.out.println("username = "+username+"，uuid = "+uuid);
    }
}
